JavaScript 解答
var twoSum = function (numbers, target) {
/** 先判斷陣列長度 **/
for (var i = 0; i < numbers.length - 1; i++) {
/** 迴圈判讀 **/
for (var j = i + 1; j < numbers.length; j++) {
/** 找出條件等於參數的陣列內值的總和的兩個索引值 **/
if (numbers[i] + numbers[j] === target) return [i, j];
}
}
};
var twoSum2 = function (numbers, target) {
var map = {};
/** 先判斷陣列長度 **/
for (var i = 0; i < numbers.length; i++) {
var n = numbers[i];
if (map[target - n] !== undefined) {
return [map[target - n], i];
} else {
map[n] = i;
}
}
};
console.log(twoSum([2, 11, 15, 7], 9));
console.log(twoSum2([2, 7, 11, 15], 9));
console.log(twoSum2([2, 7, 11, 15], 26));
console.log(twoSum2([2, 7, 11, 15], 26));
Ruby 解答
def two_sum(nums, target)
map = {}
index = 0
nums.each{|num| map[(target-num)]=index;index+=1}
puts map
for i in 0..nums.size
print i,nums[i],map[nums[i]]
if map[nums[i]] && i!=map[nums[i]]
return [i,map[nums[i]]]
end
end
return []
end